﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Threading;

using NetworkServices;
using SearchRS;


namespace SearchRS
{
    public class IdownSearcher : RSSearcher
    {
        private static SearchRS m_searchRS;
        private static ManualResetEvent m_shouldStopEvent;

        public IdownSearcher(SearchRS searchRS, ManualResetEvent shouldStopEvent)
        {
            m_searchRS = searchRS;
            m_shouldStopEvent = shouldStopEvent;
        }

        public void Search(string searchString)
        {
            for (int i = 1; i < 11; i++)
            {
                string searchLink = "http://idown.me/,downloads,search_" + searchString + "," + i + "_all_date-desc";

                AsyncWebRequest request = new AsyncWebRequest();
                request.SendWebBBRequest(searchLink, "", "", 3, "", false, "", m_shouldStopEvent, 0, "", true,
                             SearchIDownCB, searchString);

                Thread.Sleep(300);
            }
        }

        private static void SearchIDownCB(string buffer, HttpWebResponse respObj, string searchCookieParam, object userState)
        {
            if (buffer == null || buffer.Contains("לא נמצאו תוצאות למילה"))
            {
                return;
            }

            string searchString = (string)userState;

//            <a href="download_33796_השליח__גרסה_סופית_-_תרגום_מובנה___The_Messenger.html" style="font-weight: bold; color: black">
//										השליח * גרסה סופית - תרגום מובנה * / The Messenger
//									</a>
            Regex re = new Regex("a href=\"([^\"]+)\"[^>]+>([^<]+)</a>");
            MatchCollection matches = re.Matches(buffer);
            foreach (Match m in matches)
            {
                string link = m.Groups[1].Value;
                string title = Utils.Utils.CleanName(m.Groups[2].Value);
                if (Utils.Utils.AllWordsIncluded(title, searchString))
                {
                    if (title.Contains("תרגום מובנה"))
                    {
                        AsyncWebRequest request = new AsyncWebRequest();
                        link = "http://idown.me/" + link;
                        request.SendWebBBRequest(link, "", "", 3, "", false, "", m_shouldStopEvent, 0, "", true,
                                     CollectIDownLinkCB, new string[] {title, link});
                    }
                }
            }
        }

        private static void CollectIDownLinkCB(string buffer, HttpWebResponse respObj, string searchCookieParam, object userState)
        {

            if (buffer == null)
                return;

            List<string> links = new List<string>();
            string[] ctx = (string[])userState;
            string title = (string)ctx[0];
            string link = (string)ctx[1];

            Regex re = new Regex("http://www.filesonic.com/[^']+'");

            MatchCollection matches = re.Matches(buffer);
            foreach (Match m in matches)
            {
                links.Add(m.Groups[0].Value);
            }

            List<string> cleanedLinks = m_searchRS.CleanLinks(links.ToArray());
            title = Utils.Utils.CleanName(title);

            if (cleanedLinks.Count > 0)
            {
                m_searchRS.AddResult(title, link, cleanedLinks, "", "", ResultState.Verified);
            }
        }



    }
}
